package com.tboss.template.common.springSecurity;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.tboss.template.system.dto.RoleDto;
import com.tboss.global.utils.securities.algorithm.CryptoJsAesUtil;
import com.tboss.global.utils.securities.algorithm.SpringSHA;

@Service
public class SecurityBuildService {

	public static SecurityUserDto currUsrDto;
	@Autowired private SecurityService securityService;
	@Autowired private SpringSHA springSHA;
	
	public SecurityUserDto setSecurity(String username, String password){
		return this.build(username, password, true);
	}
	
	public SecurityUserDto setSecurity(String username){
		return this.build(username, null, false);
	}
	
	private SecurityUserDto build(String username, String password, Boolean isConfidential) {
		SecurityUserDto user = null;		
		String[] info;
		Boolean isEncrypt = false;
		Integer iterCnt = 500;
		String uid = username;
		String pwd = password;
	
		if(uid.indexOf(";") != -1) {
			info = uid.split(";");
			uid = info[0];
			isEncrypt = (info[1] != null && info[1].trim().length() > 0)?Boolean.parseBoolean(info[1]):isEncrypt;
			iterCnt = (info[2] != null && info[2].trim().length() > 0)?Integer.parseInt(info[2]):iterCnt;
		}		
		
		user = this.securityService.loadUserByUsername(uid);
		if (user == null) {
			throw new UsernameNotFoundException("Username not found.");//Username not found 
		}
		
		if (!user.getUsrUseYN().equals("Y")){
			throw new UsernameNotFoundException("Restricted Username.");//Username not found
		}
		
		if(isConfidential){
			pwd = (isEncrypt)?CryptoJsAesUtil.Decrypt(pwd, iterCnt):pwd;
			if (!this.springSHA.encodePassword(pwd, null).equals(user.getPassword())) {
			    throw new BadCredentialsException("Wrong password.");//Wrong password
			}
		}

		//User Group Mapping 초기화
		this.securityService.initGrpChgChkField(uid);
		
		//User Group 등록
		user.setMyGroup(this.securityService.getGroups(uid));
		
		//User ROLE 등록.
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		List<RoleDto> roles = this.securityService.getRoles(uid);
		for(RoleDto role : roles){
			authorities.add(new SimpleGrantedAuthority(role.getRoleId()));
		}
		user.setAuthorities(authorities);
		
		//User 메뉴등록
		user.setMyMenu(this.securityService.getMyMenu(uid));
		
		SecurityBuildService.currUsrDto = user;
		
		return user;
	}
	
}
